import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math.vector";
import { TargetCamera } from "@babylonjs/core/Cameras/targetCamera";
import { Scene } from "@babylonjs/core/scene";


/**
 * 切换视角
 */
class SwitchView {

    /**
     * 通用行为
     * @param scene 场景
     */
    public static generic(scene:Scene):void{
        this.lookBack(scene);
    }

    /**
     * 向后看（Y轴旋转180°）
     * @param scene 场景
     */
    public static lookBack(scene: Scene): void {
        const camera = this.getActiveCamera(scene);
        if (!camera) return;
        const rot = new Vector3;
        if (camera.rotationQuaternion) {
            camera.rotationQuaternion.toEulerAnglesToRef(rot);
            rot.y += 3.14159;
            Quaternion.FromEulerVectorToRef(rot, camera.rotationQuaternion);
        } else {
            rot.copyFrom(camera.rotation);
            rot.y += 3.14159;
            camera.rotation = rot;
        }
    }

    /**
     * 获取场景相机
     * @param scene 场景
     * @returns 相机
     */
    private static getActiveCamera(scene: Scene): TargetCamera | null {
        let cam: TargetCamera | null = null;
        if (scene.activeCamera) {
            cam = scene.activeCamera as TargetCamera;
        } else if (scene.activeCameras) {
            if (scene.activeCameras.length > 0) cam = scene.activeCameras[0] as TargetCamera;
        } else if (scene.cameras.length > 0) {
            cam = scene.cameras[0] as TargetCamera;
        }
        if (!(cam instanceof TargetCamera)) {
            console.warn('No corresponding type (TargetCamera) of camera found!')
            return null;
        }
        return cam;
    }

}


export { SwitchView };